﻿using System;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using Castle.Windsor;

namespace User.Web.UI.Helper.CastleWindsor
{
    /// <summary>
    /// Um die webApi auch über IoC nutzen zu können ist folgender Code notwendig.
    /// Und dann muss das ganze über "GlobalConfiguration.Configuration" in der Global Assax registriert werden.
    /// http://www.cafe-encounter.net/p1316/windsor-di-with-asp-net-webapi
    /// </summary>
    public class CustomWebApiControllerFactory : IHttpControllerActivator
    {
        private readonly IWindsorContainer _container;

        public CustomWebApiControllerFactory(IWindsorContainer container)
        {
            this._container = container;
        }

        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            var controller = (IHttpController)this._container.Resolve(controllerType);
            request.RegisterForDispose(new Release(() => this._container.Release(controller)));
            return controller;
        }

        private class Release : IDisposable
        {
            private readonly Action release;

            public Release(Action release)
            {
                this.release = release;
            }

            public void Dispose()
            {
                this.release();
            }
        }
    }
}